
//
//  LCUserCenterVC.m
//  LongChain
//
//  Created by FengZi on 2018/3/26.
//  Copyright © 2018年 FengZi. All rights reserved.
//

#import "LCUserCenterVC.h"
#import "LCUserCenterHeader.h"
#import "LCUserCenterCell.h"


#import "ScanViewController.h"
#import "LCPublicAlertView.h"
#import "LCUserModel.h"
#import "LCUsesModel.h"

@interface LCUserCenterVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (weak, nonatomic) IBOutlet UICollectionView *userCenterCollectionView;

@property (nonatomic, strong) NSArray *sectionTitlesData;
@property (nonatomic, strong) NSArray *sectionImagesData;
@property (nonatomic, strong) NSDictionary *userInfoDic;
@property (nonatomic, strong) NSString *devicesJsonStr;

@end

@implementation LCUserCenterVC

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.translucent = YES;


}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.navigationController.delegate = self;
    
    self.userCenterCollectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadUserInfoData];

    }];
    [self.userCenterCollectionView.mj_header beginRefreshing];

    _sectionTitlesData = @[
                     @[@"我的LCT",@"消息中心"],
                     @[@"传输列表"],
                     @[@"设备管理",@"帮助与反馈",@"关于我们"]
                     ];
    _sectionImagesData = @[
                           @[@"myChain",@"messageCenter"],
                           @[@"transferList",@"cloudList"],
                           @[@"equipmentManager",@"helpfeedback",@"about"]
                           ];
    
}


#pragma mark - - UICollectionViewDelegate
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        LCUserCenterHeader *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
        if (self.userInfoDic) {
            [header updateUserCenterHeaderWithParameter:self.userInfoDic];
        }
        
        header.uploadHeadImage = ^(id result) {
          //  上传头像
            [self updateLoadUserHeaderImage];
        };
        return header;
    }else if ([kind isEqualToString:UICollectionElementKindSectionFooter]){
        UICollectionReusableView *footer = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer" forIndexPath:indexPath];
        return footer;
    }
    return nil;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = indexPath.row;
    NSInteger section = indexPath.section;
    LCUserCenterCell *userCenterCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"userCenterCell" forIndexPath:indexPath];
    if (_sectionTitlesData.count > section) {
        NSArray *titlesData = _sectionTitlesData[section];
        NSArray *imagesData = _sectionImagesData[section];
        if (titlesData.count > row) {
            [userCenterCell lc_updateUserCenterCellWithTitle:titlesData[row] imageName:imagesData[row]];
        }
    }
    return userCenterCell;
    
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return _sectionTitlesData.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSInteger itemCount = 0;
    itemCount = [_sectionTitlesData[section] count];
    return itemCount;

}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    CGFloat height = section == 0 ? 200 : 0;
    return CGSizeMake(SWidth, height);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(SWidth, 50);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    return CGSizeMake(SWidth, 10);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NSInteger row = indexPath.row;
    NSInteger section = indexPath.section;
    switch (section) {
        case 0: //  我的链克 消息中心
        {
            switch (row) {
                case 0:  //  我的链克
                {
                    [self performSegueWithIdentifier:@"showMyLongChain" sender:self];
                }
                    break;
                case 1:  //  消息中心
                {
                    [self performSegueWithIdentifier:@"showMessageCenter" sender:self];
                }
                    
                default:
                    break;
            }
           
        }
            break;
        case 1:  //  传输列表  云添加列表
        {
            switch (row) {
                case 0:  //  传输列表
                {
                    [self performSegueWithIdentifier:@"showTransmeList" sender:self];
                }
                    break;
                case 1:  //  云添加列表
                {
                    [self performSegueWithIdentifier:@"showTransmeList" sender:self];
                }
                    break;
                    
                default:
                    break;
            }
        }
            break;
        case 2:  //  设备管理  APP设置  帮助与反馈  关于我们
        {
            switch (row) {
                case 0:  //  设备管理
                {
                    [self performSegueWithIdentifier:@"showDeviceManager" sender:self];
                }
                    break;
                case 1:  //  帮助与反馈
                {
                    [self performSegueWithIdentifier:@"showFeedback" sender:self];
                }
                    break;
                case 2:  //  关于我们
                {
                    [self performSegueWithIdentifier:@"showAbout" sender:self];
                }
                    break;
                case 4:  //  绑定设备 扫描
                {
                    [self jump];
                }
                    break;
                    
                default:
                    break;
            }
        }
            break;
        default:
            break;
    }
}

#pragma mark - -
//  更新用户头像
- (void)updateLoadUserHeaderImage {
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc]init];
        picker.delegate = self;
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:picker animated:YES completion:nil];
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    LCLog(@"%@",info);
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
    dispatch_main_async_safe(^{
        
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        if (image) {
            
            NSData *imageData = UIImagePNGRepresentation(image);
            
            [[LCNetwork shareInstance]uploadFile:imageData Path:@"/api/v0/user/avatar/update" mimeType:@"/" name:@"userHeadImage" Name:@"yang" parameter:@{} successBlock:^(id sender) {
                
                NSDictionary *data = sender[@"data"];
                NSLog(@"上传头像 = %@",data);
            } failBlock:^(id sender) {
                
            }];

        }
    });

}
//  请求用户信息
- (void)loadUserInfoData {
    
    WS(weakSelf);
    [[LCNetwork shareInstance]lc_getNetworkWithURL:@"/api/v0/user" responseSuccess:^(id resultCode, id resultParameter) {
        
        [weakSelf.userCenterCollectionView.mj_header endRefreshing];
        if ([resultCode isEqualToString:@"0"]) {
            
            NSDictionary *data = resultParameter[@"data"];
            weakSelf.userInfoDic = data;
            id devices = data[@"device"];
            if ([devices isKindOfClass:[NSArray class]] ) {
                NSArray *temp = (NSArray *)devices;
                self.devicesJsonStr = [self arrayToJSONString:temp];
                
            }
            LCUserModel *model = [LCUserModel mj_objectWithKeyValues:data];
            LCUsesModel *usermodel = [LCUsesModel usesModelStanded];
            usermodel = [LCUsesModel mj_objectWithKeyValues:data];
            
            [weakSelf.userCenterCollectionView reloadData];
        }
    } responseFail:^(id resultCode, NSError *error) {
        [weakSelf.userCenterCollectionView.mj_header endRefreshing];

    }];
}

- (NSString *)arrayToJSONString:(NSArray *)array {
    
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return jsonString;
}
#warning 扫描
- (void)jump {
    ScanViewController *vc = [[ScanViewController alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    vc.resultBlock = ^(NSString *value) {
        
        NSLog(@"value = %@",value);
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:value message:@"" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:confirmAction];
        [self presentViewController:alert animated:YES completion:nil];
        
    };
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    BOOL isShowHomePage = [viewController isKindOfClass:[self class]];
    [self.navigationController setNavigationBarHidden:isShowHomePage animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    if ([segue.identifier isEqualToString:@"showDeviceManager"]) {
         //  设备管理
        id vc = segue.destinationViewController;
        
        [vc setValue:self.devicesJsonStr forKey:@"devicesJson"];
    }
}


@end
